from common.utils.toolkit import ToolKit as tk
from common.sys.schedule import FilmSchedule as fs
import os

class Template:

    @staticmethod
    def createTemplate(filelist):
        tempfile = open(os.path.join(os.path.dirname(__file__),"resources", "head.tpt"))
        template = tempfile.read()
        tempfile.close()
        maxcol = 0
        indicators  = 0
        files = list(filelist.keys())
        while(indicators < len(files)):
            template += "<div class=\"container-fluid mt-3\"><div class=\"row\">"
            maxcol += 3
            maxcol = min(maxcol,len(files))
            while(indicators < maxcol):
                file = filelist[files[indicators]]
                template += "<div class=\"col-sm-4\"><h2>{} <small class=\"text-muted\">时长 {}</small></h2><div class=\"dropdown dropdown-menu-end\"><button type=\"button\" class=\"btn btn-primary dropdown-toggle\" data-bs-toggle=\"dropdown\">播放时刻表</button><ul class=\"dropdown-menu\">".format(file['name'], tk.translateDruation(file['duration']))
                for timestamp in fs().getTimetable(files[indicators]):
                    template += "<li><a class=\"dropdown-item\" href=\"#\">{}</a></li>".format(timestamp)
                template += "</ul></div>"
                template += "<div id=\"ind_{}\" class=\"carousel slide\" data-bs-ride=\"carousel\"><div class=\"carousel-indicators\">".format(indicators)
                for i in range(len(file['snapshot'])):
                    if(i == 0):
                        template += "<button type=\"button\" data-bs-target=\"#ind_{0}\" data-bs-slide-to=\"{1}\" class=\"active\"></button>".format(indicators, i)
                    else:
                        template += "<button type=\"button\" data-bs-target=\"#ind_{0}\" data-bs-slide-to=\"{1}\"></button>".format(indicators, i)
                template += "</div><div class=\"carousel-inner\">"
                active = True
                for snap in file['snapshot']:
                    if(active):
                        template += "<div class=\"carousel-item active\"><img src=\"data:image/jpeg;base64,{}\" class=\"d-block\" style=\"width:100%\"></div>".format(snap)
                    else:
                        template += "<div class=\"carousel-item\"><img src=\"data:image/jpeg;base64,{}\" class=\"d-block\" style=\"width:100%\"></div>".format(snap)
                    active = False
                template += "</div><button class=\"carousel-control-prev\" type=\"button\" data-bs-target=\"#ind_{0}\" data-bs-slide=\"prev\"><span class=\"carousel-control-prev-icon\"></span></button><button class=\"carousel-control-next\" type=\"button\" data-bs-target=\"#ind_{0}\" data-bs-slide=\"next\"><span class=\"carousel-control-next-icon\"></span></button></div></div>".format(indicators)
                indicators += 1
            template += "</div>"
            
        template +="</div></body></html>"
        return template.encode("utf-8")
